package com.qf.flash.ui.mine;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qf.dblib.dao.entity.UserInfo;
import com.qf.flash.R;
import com.qf.flash.base.CommonBottomChosenDialog;
import com.qf.flash.constant.Constants;
import com.qf.flash.constant.FlashCodes;
import com.qf.flash.event.UserUpdateEvent;
import com.qf.flash.model.PhotoLinesBean;
import com.qf.flash.mvp.contract.EditInformationContract;
import com.qf.flash.mvp.presenter.EditInformationPresenter;
import com.qf.flash.utils.AppToast;
import com.qf.flash.utils.ImageLoader;
import com.qf.flash.utils.LogUtil;
import com.qf.flash.utils.MyUtil;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.permission.PermissionManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qf.flash.constant.Constants.ALBUM_RESULT_CODE;
import static com.qf.flash.constant.Constants.CAMERA_RESULT_CODE;
import static com.qf.flash.constant.Constants.CHANG_HEAD_FRAME;
import static com.qf.flash.constant.Constants.CHANG_NICKNAME;
import static com.qf.flash.constant.Constants.CHANG_SIGN;
import static com.qf.flash.utils.UriTool.getRealPathFromUri;

public class EditInformationActivity extends BaseActivity implements EditInformationContract.View {
    @BindView(R.id.tv_top_back)
    TextView tvTopBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_top_right)
    TextView tvTopRight;
    @BindView(R.id.ll_head)
    LinearLayout llHead;
    @BindView(R.id.ll_nick)
    LinearLayout llNick;
    @BindView(R.id.ll_sex)
    LinearLayout llSex;

    @BindView(R.id.ll_autograph)
    LinearLayout llAutograph;
    @BindView(R.id.ll_head_circle)
    LinearLayout llHeadCircle;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_autograph)
    TextView tvAutograph;
    @BindView(R.id.iv_head_circle)
    ImageView ivHeadCircle;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    private Uri photoUri;
    private Uri caUri;
    private UserInfo userInfo;
    private String picPath;
    private EditInformationPresenter informationPresenter;
    private String sexCode;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_information;
    }

    @Override
    protected void initViewAndData() {
        tvTopTitle.setText("编辑资料");
        tvTopRight.setText("保存");
        getIntentData();
        initView();
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    private void getIntentData() {
        userInfo = (UserInfo) getIntent().getSerializableExtra("info");
    }

    private void initView() {
        // 头像
        ImageLoader.loadCircleHead(ivHead.getContext(), userInfo.getPhoto(), ivHead);
        // 昵称
        if (MyUtil.isNullOrEmpty(userInfo.getName())) {
            tvNickName.setText("请输入昵称");
        } else {
            tvNickName.setText(userInfo.getName());
        }
        // 性别
        switch (userInfo.getSex()) {
            case FlashCodes.SEX_MAN:
                tvSex.setText("男");
                break;
            case FlashCodes.SEX_FEMALE:
                tvSex.setText("女");
                break;
            default:

                break;
        }
        if (MyUtil.isNullOrEmpty(userInfo.getSign())) {
            tvAutograph.setText("您还没有签名哦，输入签名吧！");
        }else {
            tvAutograph.setText(userInfo.getSign());
        }

        tvId.setText(userInfo.getUid());
        ImageLoader.loadFit(this, userInfo.getPhotoLineImage(), ivHeadCircle);

    }


    @Override
    protected void initInject() {
        super.initInject();
        informationPresenter = new EditInformationPresenter();
        initPresenters(informationPresenter);
    }

    //
    @OnClick({R.id.tv_top_back, R.id.ll_top_right, R.id.ll_head, R.id.ll_nick, R.id.ll_sex, R.id.ll_autograph, R.id.ll_head_circle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:// 返回按钮
                finish();
                break;
            case R.id.ll_top_right://保存
                informationPresenter.submitInfo(userInfo);
                break;
            case R.id.ll_head:// 设置头像
                showPictureChosenDialog();
                break;
            case R.id.ll_nick://编辑昵称
                Intent intent = new Intent(this, EditNicknameActivity.class);
                intent.putExtra("nickName", userInfo.getName());
                startActivityForResult(intent, CHANG_NICKNAME);
                break;
            case R.id.ll_sex://性别
                showSexChosenDialog();
                break;

            case R.id.ll_autograph://编辑签名
                Intent intent2 = new Intent(this, EditAutographActivity.class);
                intent2.putExtra(Constants.CHANGED_SIGN, tvAutograph.getText().toString().trim());
                startActivityForResult(intent2, CHANG_SIGN);
                break;
            case R.id.ll_head_circle:
                Intent intent3 = new Intent(this, ChooseHeadFrameActivity.class);
                intent3.putExtra(Constants.CHANGED_SIGN, tvAutograph.getText().toString().trim());
                startActivityForResult(intent3, CHANG_HEAD_FRAME);

                break;
        }
    }

    public static void start(Activity activity, UserInfo userInfo) {
        Intent intent = new Intent(activity, EditInformationActivity.class);
        intent.putExtra("info", userInfo);
        activity.startActivity(intent);
    }

    private void requestPermission(int pos) {
        new PermissionManager(this)
                .addPermission(Constants.TAKE_PHOTO_PERMISSION)
                .addListener(new PermissionManager.OnPermissionListener() {
                    @Override
                    public void onSuccess(List<String> permissions) {
                        if (pos == 0)
                            openSysCamera();
                        else
                            openSysAlbum();
                    }

                    @Override
                    public void onFailed(List<String> permissions) {
                        FlashLib.showToast("权限拒绝");
                    }
                });
    }

    /**
     * 选择性别弹框
     */
    private void showSexChosenDialog() {
        String[] data = {"男", "女"};
        CommonBottomChosenDialog.newInstance()
                .setData(data)
                .setOnItemClickListener((view, position) -> {
                    if (position == 0) {
                        tvSex.setText(((TextView) view).getText());
                        sexCode = FlashCodes.SEX_MAN;

                    } else {
                        tvSex.setText(((TextView) view).getText());
                        sexCode = FlashCodes.SEX_FEMALE;
                    }
                    userInfo.setSex(sexCode);
                }).show(getSupportFragmentManager());
    }

    /**
     * 选择头像弹框
     */
    private void showPictureChosenDialog() {
        String[] data = {"拍照", "相册"};
        CommonBottomChosenDialog.newInstance()
                .setData(data)
                .setOnItemClickListener((view, position) -> {
                    requestPermission(position);
                }).show(getSupportFragmentManager());
    }

    /**
     * 打开系统相机
     */
    private void openSysCamera() {
        File appDir = new File(Environment.getExternalStorageDirectory(), "test");
        if (!appDir.exists()) {
            appDir.mkdir();
        }

        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);

        picPath = file.getAbsolutePath();

        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);

        // 把文件地址转换成Uri格式
        caUri = Uri.fromFile(new File(picPath));
        if (Build.VERSION.SDK_INT >= 24) {
            caUri = FileProvider.getUriForFile(this, "com.qf.flash.provider", new File(picPath));
        } else {
            caUri = Uri.fromFile(new File(picPath));
        }
        //设置系统相机拍摄照片完成后图片文件的存放地址
        intent.putExtra(MediaStore.EXTRA_OUTPUT, caUri);
        startActivityForResult(intent, CAMERA_RESULT_CODE);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //  拍照返回
                case CAMERA_RESULT_CODE:
                    if (data == null) {
                        ImageLoader.loadCircleHead(ivHead.getContext(), picPath, ivHead);
                        userInfo.setPhoto(picPath);
                        return;
                    }
                    caUri = data.getData();
                    if (caUri == null) {
                        AppToast.showToast("返回照片错误");
                        return;
                    } else {
                        String realPathFromUri = getRealPathFromUri(this, caUri);
                        userInfo.setPhoto(realPathFromUri);
                        ImageLoader.loadCircleHead(ivHead.getContext(), realPathFromUri, ivHead);
                    }

                    break;
                //  相册返回
                case ALBUM_RESULT_CODE:

                    LogUtil.e("是否进入相册返回值");
                    if (data == null) {
                        AppToast.showToast("选择图片文件出错");
                        return;
                    }
                    photoUri = data.getData();
                    if (photoUri == null) {
                        AppToast.showToast("返回照片错误");
                        return;
                    } else {
                        String realPathFromUri = getRealPathFromUri(this, photoUri);
                        userInfo.setPhoto(realPathFromUri);
                        ImageLoader.loadCircleHead(ivHead.getContext(), realPathFromUri, ivHead);

                    }
                    break;
                //  昵称修改返回
                case CHANG_NICKNAME:
                    String newName = data.getStringExtra(Constants.CHANGED_NICKNAME);
                    if (!MyUtil.isNullOrEmpty(newName)) {
                        tvNickName.setText(newName);
                        userInfo.setName(newName);
                    }
                    break;

                case CHANG_SIGN:
                    String newSign = data.getStringExtra(Constants.CHANGED_SIGN);
                    if (!MyUtil.isNullOrEmpty(newSign)) {
                        tvAutograph.setText(newSign);
                        userInfo.setSign(newSign);
                    }
                    break;
                default:
                    LogUtil.e("是否进入默认返回值");
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void openSysAlbum() {
        Intent albumIntent = new Intent();
        Intent intent = getGalleryIntent(albumIntent);
        startActivityForResult(intent, ALBUM_RESULT_CODE);
    }

    public static Intent getGalleryIntent(Intent intent) {    /**19之后的系统相册的图片都存在于MediaStore数据库中；19之前的系统相册中可能包含不存在与数据库中的图片，所以如果是19之上的系统     * 跳转到19之前的系统相册选择了一张不存在与数据库中的图片，解析uri时就可能会出现null*/
        if (Build.VERSION.SDK_INT < 19) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        }
        return intent;
    }

    // 保存用户信息成功
    @Override
    public void onSubmitSuccess() {
        EventBus.getDefault().post(new UserUpdateEvent());
        FlashLib.showToast("保存用户信息成功");
    }

    // 保存用户信息失败
    @Override
    public void onSubmitFailed() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPhotoLineEvent(PhotoLinesBean bean) {
        if (userInfo != null) {
            userInfo.setPhotoLine(bean.getId());
            userInfo.setPhotoLineImage(bean.getImage());
            ImageLoader.loadCircle(this, userInfo.getPhotoLineImage(), ivHeadCircle);
        }


    }
}
